import { Workbook } from "exceljs";
import { saveAs } from "file-saver";

export default function exportExcel(
  columns: any[],
  data: any[],
  title: string
) {
  // 创建一个新的工作簿
  const workbook = new Workbook();
  const worksheet = workbook.addWorksheet("Sheet 1");

  // 定义列标题
  const filterColumns = columns.filter(v => v.title && v.property !== "action");
  const headers = filterColumns.map(v => v.title);
  headers.unshift("序号");
  const columnKeys = filterColumns.map(v => v.field);
  // 将列标题添加到第一行
  worksheet.addRow(headers);

  // 准备数据
  // const data = [
  //   { id: 1, name: "Alice", age: 30 },
  //   { id: 2, name: "Bob", age: 25 },
  //   { id: 3, name: "Charlie", age: 35 }
  // ];

  // 将数据添加到工作表中
  data.forEach((row, i) => {
    const rowData = [i];
    for (const key of columnKeys) {
      rowData.push(row[key]);
    }
    worksheet.addRow(rowData);
  });

  // 保存文件
  workbook.xlsx
    .writeBuffer()
    .then(buffer => {
      // 生成excel文件的二进制数据
      saveAs.saveAs(
        new Blob([buffer], {
          // 生成Blob对象
          type: "application/octet-stream" // 指定文件的MIME类型
        }),
        title + ".xlsx"
      ); // 指定文件名
    })
    .catch(error => {
      console.error("写入文件时出错:", error);
    });
}
